
package com.bluelinelabs.conductor.conductor.changehandler;

import ohos.aafwk.content.IntentParams;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;

import com.bluelinelabs.conductor.conductor.Controller;
import com.bluelinelabs.conductor.conductor.ControllerChangeHandler;


/**
 * lipeiquan
 *
 * @since 2021-05-06
 */
public class SimpleSwapChangeHandler extends ControllerChangeHandler implements Component.BindStateChangedListener {

    private static final String KEY_REMOVES_FROM_ON_PUSH = "SimpleSwapChangeHandler.removesFromViewOnPush";

    private boolean removesFromViewOnPush;

    private boolean canceled;

    private ControllerChangeCompletedListener changeListener;

    public SimpleSwapChangeHandler() {
        this(true);
    }

    public SimpleSwapChangeHandler(boolean removesFromViewOnPush) {
        this.removesFromViewOnPush = removesFromViewOnPush;
    }

    @Override
    public void saveToBundle(IntentParams bundle) {
        super.saveToBundle(bundle);
        bundle.setParam(KEY_REMOVES_FROM_ON_PUSH, removesFromViewOnPush);
    }

    @Override
    public void restoreFromBundle(IntentParams bundle) {
        super.restoreFromBundle(bundle);
        removesFromViewOnPush = (boolean) bundle.getParam(KEY_REMOVES_FROM_ON_PUSH);
    }

    @Override
    public void onAbortPush(ControllerChangeHandler newHandler, Controller newTop) {
        super.onAbortPush(newHandler, newTop);

        canceled = true;
    }

    @Override
    public void completeImmediately() {
        if (changeListener != null) {
            changeListener.onChangeCompleted();
            changeListener = null;
        }
    }

    @Override
    public void performChange(ComponentContainer container, Component from, Component to, boolean isPush, ControllerChangeCompletedListener changeListener) {
        if (!canceled) {
            if (from != null && (!isPush || removesFromViewOnPush)) {
                container.removeComponent(from);
            }
            if (to != null && to.getComponentParent() == null) {
                container.addComponent(to);
            }
        }
        if (container.getTag() != null) {
            changeListener.onChangeCompleted();
        } else {
            this.changeListener = changeListener;
            container.setBindStateChangedListener(this);
        }
    }

    @Override
    public boolean removesFromViewOnPush() {
        return removesFromViewOnPush;
    }


    @Override
    public ControllerChangeHandler copy() {
        return new SimpleSwapChangeHandler(removesFromViewOnPush());
    }

    @Override
    public boolean isReusable() {
        return true;
    }

    @Override
    public void onComponentBoundToWindow(Component v) {
        if (changeListener != null) {
            changeListener.onChangeCompleted();
            changeListener = null;
        }
    }

    @Override
    public void onComponentUnboundFromWindow(Component v) {

    }
}
